<template>
  <div class="image-annotation-container">
    <div class="control-panel">
      <h3>矩形标注工具</h3>
      <div class="control-group">
        <label>
          宽度: <input type="number" v-model.number="rectWidth" min="10">
        </label>
        <label>
          高度: <input type="number" v-model.number="rectHeight" min="10">
        </label>
        <button @click="clearAll">清除所有</button>
      </div>

      <div class="coordinates-display" v-if="selectedRect">
        <h4>当前矩形坐标 (右下角为原点):</h4>
        <ul>
          <li>左上角: ({{ selectedRect.coordinates.topLeft.x.toFixed(2) }}, {{ selectedRect.coordinates.topLeft.y.toFixed(2) }})</li>
          <li>右上角: ({{ selectedRect.coordinates.topRight.x.toFixed(2) }}, {{ selectedRect.coordinates.topRight.y.toFixed(2) }})</li>
          <li>左下角: ({{ selectedRect.coordinates.bottomLeft.x.toFixed(2) }}, {{ selectedRect.coordinates.bottomLeft.y.toFixed(2) }})</li>
          <li>右下角: ({{ selectedRect.coordinates.bottomRight.x.toFixed(2) }}, {{ selectedRect.coordinates.bottomRight.y.toFixed(2) }})</li>
        </ul>
      </div>
    </div>

    <div class="image-container" ref="imageContainer">
      <img
        ref="targetImage"
        src="https://picsum.photos/800/600"
        alt="标注目标图片"
        @load="initCanvas"
      >
      <canvas
        ref="annotationCanvas"
        class="annotation-canvas"
        @click="handleCanvasClick"
        @mousedown="handleMouseDown"
      ></canvas>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 矩形属性
      rectWidth: 100,
      rectHeight: 80,
      rectangles: [],
      selectedRect: null,
      // 拖拽状态
      isResizing: false,
      resizeHandle: null,
      startX: 0,
      startY: 0,
      // 画布和图片尺寸
      canvasWidth: 0,
      canvasHeight: 0,
      imageWidth: 0,
      imageHeight: 0
    };
  },
  methods: {
    // 初始化画布
    initCanvas() {
      const image = this.$refs.targetImage;
      const canvas = this.$refs.annotationCanvas;
      const container = this.$refs.imageContainer;

      // 设置画布尺寸与图片一致
      this.imageWidth = image.offsetWidth;
      this.imageHeight = image.offsetHeight;
      this.canvasWidth = this.imageWidth;
      this.canvasHeight = this.imageHeight;

      canvas.width = this.canvasWidth;
      canvas.height = this.canvasHeight;

      // 设置画布位置覆盖图片
      canvas.style.width = `${this.canvasWidth}px`;
      canvas.style.height = `${this.canvasHeight}px`;
    },

    // 处理画布点击事件 - 创建新矩形
    handleCanvasClick(e) {
      // 如果正在调整大小，不创建新矩形
      if (this.isResizing) return;

      const canvas = this.$refs.annotationCanvas;
      const rect = canvas.getBoundingClientRect();

      // 计算点击位置在画布上的坐标
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;

      // 创建新矩形
      const newRect = {
        id: Date.now(), // 使用时间戳作为唯一ID
        x,
        y,
        width: this.rectWidth,
        height: this.rectHeight,
        coordinates: {}
      };

      this.rectangles.push(newRect);
      this.selectedRect = newRect;
      this.updateCoordinates(newRect);
      this.drawRectangles();
    },

    // 处理鼠标按下事件 - 开始调整大小
    handleMouseDown(e) {
      const canvas = this.$refs.annotationCanvas;
      const rect = canvas.getBoundingClientRect();
      const mouseX = e.clientX - rect.left;
      const mouseY = e.clientY - rect.top;

      // 检查是否点击了某个矩形的调整手柄
      for (let i = this.rectangles.length - 1; i >= 0; i--) {
        const r = this.rectangles[i];
        // 检查是否点击了右下角调整手柄（10px范围）
        if (
          mouseX >= r.x + r.width - 10 &&
          mouseX <= r.x + r.width + 10 &&
          mouseY >= r.y + r.height - 10 &&
          mouseY <= r.y + r.height + 10
        ) {
          this.isResizing = true;
          this.resizeHandle = 'bottomRight';
          this.selectedRect = r;
          this.startX = mouseX;
          this.startY = mouseY;

          // 添加鼠标移动和释放事件监听
          document.addEventListener('mousemove', this.handleMouseMove);
          document.addEventListener('mouseup', this.handleMouseUp);
          e.preventDefault();
          return;
        }
      }
    },

    // 处理鼠标移动事件 - 调整大小
    handleMouseMove(e) {
      if (!this.isResizing || !this.selectedRect) return;

      const canvas = this.$refs.annotationCanvas;
      const rect = canvas.getBoundingClientRect();
      const mouseX = e.clientX - rect.left;
      const mouseY = e.clientY - rect.top;

      // 计算尺寸变化
      const deltaX = mouseX - this.startX;
      const deltaY = mouseY - this.startY;

      // 调整矩形大小（确保最小尺寸）
      if (this.resizeHandle === 'bottomRight') {
        this.selectedRect.width = Math.max(10, this.selectedRect.width + deltaX);
        this.selectedRect.height = Math.max(10, this.selectedRect.height + deltaY);
      }

      // 更新起始位置和画布
      this.startX = mouseX;
      this.startY = mouseY;
      this.updateCoordinates(this.selectedRect);
      this.drawRectangles();
    },

    // 处理鼠标释放事件 - 结束调整大小
    handleMouseUp() {
      this.isResizing = false;
      this.resizeHandle = null;

      // 移除事件监听
      document.removeEventListener('mousemove', this.handleMouseMove);
      document.removeEventListener('mouseup', this.handleMouseUp);
    },

    // 更新矩形坐标（转换为以图片右下角为原点）
    updateCoordinates(rect) {
      // 原canvas坐标：左上角为(0,0)，向右x增大，向下y增大
      // 目标坐标：右下角为(0,0)，向左x增大，向上y增大

      const bottomRightX = this.canvasWidth;
      const bottomRightY = this.canvasHeight;

      rect.coordinates = {
        topLeft: {
          x: bottomRightX - rect.x - rect.width,
          y: bottomRightY - rect.y - rect.height
        },
        topRight: {
          x: bottomRightX - rect.x,
          y: bottomRightY - rect.y - rect.height
        },
        bottomLeft: {
          x: bottomRightX - rect.x - rect.width,
          y: bottomRightY - rect.y
        },
        bottomRight: {
          x: bottomRightX - rect.x,
          y: bottomRightY - rect.y
        }
      };
    },

    // 绘制所有矩形
    drawRectangles() {
      const canvas = this.$refs.annotationCanvas;
      const ctx = canvas.getContext('2d');

      // 清除画布
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // 绘制所有矩形
      this.rectangles.forEach(rect => {
        ctx.beginPath();
        ctx.rect(rect.x, rect.y, rect.width, rect.height);
        ctx.strokeStyle = '#ff0000';
        ctx.lineWidth = 2;
        ctx.stroke();

        // 绘制右下角调整手柄
        ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
        ctx.fillRect(rect.x + rect.width - 10, rect.y + rect.height - 10, 10, 10);
      });
    },

    // 清除所有矩形
    clearAll() {
      this.rectangles = [];
      this.selectedRect = null;
      this.drawRectangles();
    }
  },
  watch: {
    // 当矩形数组变化时重新绘制
    rectangles: {
      deep: true,
      handler() {
        this.drawRectangles();
      }
    }
  },
  mounted() {
    // 监听窗口大小变化，重新调整画布
    window.addEventListener('resize', () => {
      if (this.$refs.targetImage.complete) {
        this.initCanvas();
        this.rectangles.forEach(rect => this.updateCoordinates(rect));
        this.drawRectangles();
      }
    });
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.initCanvas);
    document.removeEventListener('mousemove', this.handleMouseMove);
    document.removeEventListener('mouseup', this.handleMouseUp);
  }
};
</script>

<style scoped>
.image-annotation-container {
  display: flex;
  flex-direction: column;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.control-panel {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.control-group {
  display: flex;
  gap: 15px;
  margin: 15px 0;
  align-items: center;
  flex-wrap: wrap;
}

.control-group input {
  width: 80px;
  padding: 5px;
}

.control-group button {
  padding: 5px 15px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.control-group button:hover {
  background-color: #359e75;
}

.coordinates-display {
  margin-top: 15px;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
}

.coordinates-display ul {
  margin: 10px 0;
  padding-left: 20px;
}

.image-container {
  position: relative;
  display: inline-block;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.annotation-canvas {
  position: absolute;
  top: 0;
  left: 0;
  cursor: crosshair;
}

img {
  max-width: 100%;
  height: auto;
  display: block;
}
</style>
